﻿
Ext.ns('ExtSensorList');
ExtSensorList.version = 'Beta 1';
var g_ExtSensorWindowObject;

function trackerExtendSensorWin(autoload){
    function msgUpdateSuccess() {
        Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
        Ext.Msg.show({
            title: _CustomerConfigResource_Tip,
            msg: _CustomerConfigResource_Success,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.INFO
        });
    };
    
    function msgUpdateFailure() {
        Ext.MessageBox.buttonText.ok = _CustomerConfigResource_OK;
        Ext.Msg.show({
            title: _CustomerConfigResource_Tip,
            msg: _CustomerConfigResource_Failure,
            buttons: Ext.Msg.OK,
            animEl: 'elId',
            icon: Ext.MessageBox.WARNING
        });
    }
    
    var pagesize = 65535;
    var extsensorfield = [{name:"choosed",type:"boolean"},"id", "sssid", "trackername", {name:"protocol_ver",type:'integer'}, {name:'sensor_number',type:'integer'}, "expression", { name: "registered", type: "bool" }, "sensor_sn",{name:'maxvalue',type:'float'},{name:'minvalue',type:'float'},{name:'maxalarm',type:'bool'},{name:'minalarm',type:'bool'},'unit','lasttime','lastvalue', 'btn','btnQuickReport'];
    
    var trackNameCombo = getTrackerCheckboxCombo(true);
    
    var txtSearchSensorName = new Ext.form.TextField({
    
    });
    
    var txtSearchSensorSN = new Ext.form.TextField({
    });
    
    var extsensorstore = new Ext.data.GroupingStore({
	   proxy:new Ext.data.HttpProxy({
            url:"Handler/HandlerSearchExtendSensor",
            method:"POST",
            timeout:120000
       }),
       reader:new Ext.data.JsonReader({
			fields:extsensorfield,
            root:"data",
            totalProperty: "totalCount"
       }),
       sortInfo:{field: 'trackername', direction: "ASC"},
       groupField:'trackername'
   });
   
   var grdviewgroup = new Ext.grid.GroupingView({
        startCollapsed: false,
        //forceFit:true,
        groupTextTpl: '{gvalue}'
    });
   
   extsensorstore.addListener('load', function(store, records) {
        if(showfahrenheit){
            store.each(function(record){
                record.set('maxvalue',Celsius2Fahrenheit(record.get('maxvalue'))); //C to F
                record.set('minvalue',Celsius2Fahrenheit(record.get('minvalue'))); //C to F
            });
        }
        
        lastlocationintervalstore.each(function(r){
            for(t in r.json){
                var fname = t;
                if(fname.indexOf("01") != -1 && fname.length == 4){
                    if(fname !='01FF'){
                        var v = parseFloat(r.json[t]);
                        var sensornumber = parseInt(fname.substr(2,2),16);
                        if(showfahrenheit){
                            v = Celsius2Fahrenheit(v);
                        }
                        v = v.toFixed(2);
                        var index = extsensorstore.findBy(function(record,id){
                            return record.get("sssid") == r.get('sssid') && record.get("sensor_number")== sensornumber;
                        });
                        if(index != -1){
                            var record = extsensorstore.getAt(index);
                            record.set('lasttime',r.get('receivedtime'));
                            record.set('lastvalue',v);
                        }
                    }
                }
            }
        });
   });
   
   extsensorstore.on('beforeload',function(store){
        extsensorstore.baseParams = {sssids: trackNameCombo.getValue()} 
   });
   
   if(Ext.isDefined(autoload)){
        extsensorstore.reload({
            params: {
                sssids:'',
                start: 0,
                limit: pagesize,
                autoload:1
            }
        });
   }


   var tbar = new Ext.Toolbar({
       items: [
            _Alarm_TrackerName + ':',
            trackNameCombo,
            _Sensor_Name + ':',
            txtSearchSensorName,
            'SN:',
            txtSearchSensorSN,
            {
                tooltip: { text: _TrackerMain_Search, autoHide: true },
                icon: 'images/search16.gif',
                handler: function() {
                    extsensorstore.reload({
                        params: {
                            sssids: trackNameCombo.getValue(),
                            sensorname: txtSearchSensorName.getValue(),
                            sensorsn: txtSearchSensorSN.getValue(),
                            start: 0,
                            limit: pagesize
                        }
                    });
                }
            }, {
                tooltip: { text: _CustomerConfigResource_Delete, autoHide: true },
                icon: 'images/delete.png',
                handler: function() {
                    Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                    Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn) {
                        if (btn == "yes") {
                            sensoreditor.stopEditing();
                            Ext.MessageBox.show({
                                msg: _CustomerConfigResource_Deleting,
                                progressText: _CustomerConfigResource_Deleting,
                                width: 300,
                                wait: true,
                                waitConfig: { interval: 200 }
                            });
                            //                            var s = grid.getSelectionModel().getSelections();
                            //                            var splitIds = "";
                            //                            for (var j = 0; j < s.length; j++) {
                            //                                if (s.length == 1) {
                            //                                    splitIds = s[j].data.id;
                            //                                }
                            //                                else {

                            //                                    if (j < (s.length - 1)) {
                            //                                        splitIds = s[j].data.id + "," + splitIds;
                            //                                    }
                            //                                    if (j == (s.length - 1)) {
                            //                                        splitIds = splitIds + s[j].data.id;
                            //                                    }
                            //                                }
                            //                            }

                            var splitIds = "";
                            extsensorstore.each(function(record) {
                                if (record.get('choosed')) {
                                    if (splitIds.length == "") {
                                        splitIds = record.get("id");
                                    }
                                    else {
                                        splitIds += "," + record.get("id");
                                    }
                                }

                            });
                            if (splitIds.length > 0) {

                                Ext.Ajax.request({
                                    url: 'Handler/HandlerDelExtendSensor',
                                    success: function(result) {
                                        Ext.MessageBox.hide();
                                        var flag = eval(result.responseText);
                                        if (flag != "false") {
                                            extsensorstore.each(function(r) {
                                                if (r.get('choosed'))
                                                    extsensorstore.remove(r);
                                            });
                                            Ext.Msg.alert(_CustomerConfigResource_Tip, _CustomerConfigResource_Deleted);
                                        }
                                        else {
                                            Ext.Msg.alert(_CustomerConfigResource_Tip, _RouteResources_Failed);
                                        }
                                    },
                                    failure: function() {
                                        Ext.MessageBox.hide();
                                        Ext.Msg.alert(_CustomerConfigResource_Tip, _RouteResources_Failed);
                                    },
                                    params: {
                                        splitIds: splitIds,
                                        HandlerType: 'Delete'
                                    }
                                })
                            }
                            else {
                                Ext.Msg.alert(_CustomerConfigResource_Tip,_POI_SelectAtLeastOne);
                            }
                        }
                        
                    });
                }
            }
       ]
   });
   
   var txtsensorname = new Ext.form.TextField({
        allowBlank: false,
        blankText: _CustomerConfigResource_CanNotEmpty,
        maxLength:15,
        listeners: {
            render: function(c) {
              c.getEl().on({
                //change: handlerChange,
                keyup: handlerChange,
                scope: c
              });
            }
        }
    });
   
   function handlerChange(){
       if (isUnicode(txtsensorname.getValue())) {
           txtsensorname.maxLength = 8;
       }
       else{
           txtsensorname.maxLength = 15;
       }
       var v = txtsensorname.getValue().replace(/#/g, "");
       txtsensorname.setValue(v);
   }
   
   var btnSelectAll = new Ext.Button({
        text: _Photo_SelectAll,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            extsensorstore.each(function(record) {
                record.set("choosed", true);
            });
        }
    });

    var btnSelectNone = new Ext.Button({
        text: _Photo_SelectNone,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            extsensorstore.each(function(record) {
                record.set("choosed", false);
            });
        }
    });
    
    var btnUnregister = new Ext.Button({
        text:_TrackerMain_Unregister,
        style: 'margin-right:16px',
        width: 80,
        
        handler: function() {
            var sssidarray =[];
            var commandarray=[];
            var paramarray=[];
            var tmp="";
            extsensorstore.each(function(record) {
                
                if(record.get("choosed")){
                    var sssid = record.get("sssid");
                    if(sssid != tmp){
                        tmp = sssid;
                        sssidarray.push(sssid);
                        commandarray.push(EnumMT88Command.Del_Ext_Sensor);
                        paramarray.push( UInt8ToByteString(record.get("sensor_number")));
                    }
                    else{
                        paramarray[paramarray.length-1] +="," + UInt8ToByteString(record.get("sensor_number"));
                    }
                }
            });
            addTCPCommandWithDiffParamForMT(sssidarray,commandarray,paramarray);
        }
    });
    
    var btnSaveFirstChoosedToAll = new Ext.Button({
        text:  _TrackerMain_BatchUpdate,
        style: 'margin-right:16px',
        width: 80,
        disabled:true,
        handler: function() {
            Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
            Ext.MessageBox.confirm(_TrackerMain_Title, _Message_SureToUpdateToAll, function(btn){
                if (btn == "yes") {
                    Ext.MessageBox.show({
                        msg: _CustomerConfigResource_Saving,
                        progressText: _CustomerConfigResource_Saving,
                        width: 300,
                        wait: true,
                        waitConfig: { interval: 200 }
                    });
                    var sensorids ="";
                    var maxvalue="";
                    var minvalue="";
                    var maxalarm="";
                    var minalarm="";
                    var sssidarray=[];
                    var mt88commandArray=[];
                    var mt88paramArray=[];
                    var tmpsssid="";
                    extsensorstore.each(function(record) {
                        if(maxvalue==""){
                            if(record.get("choosed")){
                                maxvalue = showfahrenheit?Fahrenheit2Celsius(record.get("maxvalue")):record.get("maxvalue");
                                minvalue = showfahrenheit?Fahrenheit2Celsius(record.get("minvalue")):record.get("minvalue");
                                maxalarm = record.get("maxalarm");
                                minalarm = record.get("minalarm");
                            }
                        }
                        sensorids += (sensorids.length==0?"":",") + record.get('id');
                        if(tmpsssid != record.get("sssid")){
                            sssidarray.push(record.get("sssid"));
                            mt88commandArray.push("C46");
                            mt88paramArray.push("");
                            tmpsssid =  record.get("sssid");
                        }
                    });
                    
                    Ext.Ajax.request({
                        url: 'Handler/HandlerUpdateExtendSensor',
                        success: function(result) {
                            Ext.MessageBox.hide();
                            sensoreditor.stopEditing();
                            var flag = eval(result.responseText);
                            if (flag == true) {
                                msgUpdateSuccess();
                                addTCPCommandWithDiffParamForMT(sssidarray,mt88commandArray,mt88paramArray);
                            }
                            else {
                                msgUpdateFailure();
                            }
                        },
                        failure: function() {
                            Ext.MessageBox.hide();
                            msgUpdateFailure();
                        },
                        params: {
                            updatetoall:1,
                            sensorids: sensorids,
                            maxvalue: showfahrenheit?Fahrenheit2Celsius(maxvalue):maxvalue,
                            minvalue: showfahrenheit?Fahrenheit2Celsius(minvalue):minvalue,
                            maxalarm:maxalarm,
                            minalarm:minalarm
                        }
                    })
                }
            });
        }
    });
  
     var btn= new Ext.ux.grid.CellActions({
        iconIndex: 'btn',
        qtipIndex: 'btn'
    });
    
    var btnQuickReport = new Ext.ux.grid.CellActions({
        iconIndex: 'btnQuickReport',
        qtipIndex: 'btnQuickReport'
    });
    var choosebox = new Ext.form.Checkbox({
        allowBlank: true,
        maxLength:3
   });
   
    var checkExtSensor = new Ext.grid.CheckColumn({
       header: '',
       width:25,
       sortable: false,
       dataIndex: 'choosed',
       editor:choosebox
       //,fixed:true
    });
    
    extsensorstore.on('update',function(){
        var hasonechoosed = false;
         extsensorstore.each(function(record) {
            if(record.get('choosed')){
                hasonechoosed = true;
                return;
            }
         });
         if(hasonechoosed){
            btnSaveFirstChoosedToAll.setDisabled(false);
         }
         else
            btnSaveFirstChoosedToAll.setDisabled(true);
    });
   

    
     
   
    var sensoreditor = new Ext.ux.grid.RowEditor({
        saveText: _CustomerConfigResource_Update,
        cancelText: _CustomerConfigResource_Cancel,
        listeners: {
            afteredit: function(obj, chas, rec, rowindex1) {
                updateExtendSensor();
            }
        }
    });


    ExtSensorList.Grid = Ext.extend(Ext.grid.EditorGridPanel, {
        initComponent: function() {
            this.action = new Ext.ux.grid.RowActions({
                    header: ''
                      , autoWidth: true
                    , keepSelection: false
                    , actions: [{
                        iconCls: 'icon-unregister'
                        , qtip: _TrackerMain_Unregister
                    }, {
                        iconCls: 'icon-quickly-report'
                        , qtip: _TrackerMain_QuickReport
                    }]
                    , callbacks: {
                        'icon-led-edit': function(grid, record, action, row, col) {

                        }
                    }
                });
                this.action.on({
                    action: function(grid, record, action, row, col) {
                        //Ext.ux.Toast.msg('Event: action', 'You have clicked row: <b>{0}</b>, action: <b>{1}</b>', row, action);
                        if (action == 'icon-register') {
                            var sssid = record.get('sssid');
                            var sensor_sn = record.get('sensor_sn');
                            var sensor_number = record.get('sensor_number');
                            var mt88cmd = EnumMT88Command.Reg_Ext_Sensor;
                            var mt88param = sensor_sn + "," + sensor_number.toString();
                            var gvvtcommand = EnumGPRSCommand.NotSupportThisCommand;
                            var gvvtparam = "";
                            var gbcommand = "";
                            var gbparam = "";
                            if (sssid != "")
                                addOneTCPCommand(sssid, gvvtcommand, gvvtparam, mt88cmd, mt88param, gbcommand, gbparam);
                        }
                        else if (action == 'icon-unregister') {
                            Ext.MessageBox.YESNO = { yes: _TrackerMain_Yes, no: _TrackerMain_No };
                            Ext.MessageBox.confirm(_TrackerMain_Title, _Photo_SureToDelete, function(btn) {
                                if (btn == "yes") {
                                    var sssid = record.get('sssid');
                                    var sensor_number = record.get('sensor_number');
                                    var mt88cmd = EnumMT88Command.Del_Ext_Sensor;
                                    var mt88param = UInt8ToByteString(sensor_number);
                                    var gvvtcommand = EnumGPRSCommand.NotSupportThisCommand;
                                    var gvvtparam = "";
                                    var gbcommand = "";
                                    var gbparam = "";
                                    if (sssid != "")
                                        addOneTCPCommand(sssid, gvvtcommand, gvvtparam, mt88cmd, mt88param, gbcommand, gbparam);
                                }
                            });

                        }
                        else if (action == 'icon-quickly-report') {
                            var sensorid = parseInt(record.get('sensor_number')) + 0x0100;
                            calculateUnderTimeWindow(record.get('sssid'), sensorid);
                        }
                    }
                });

                Ext.apply(this, {
                    colModel: new Ext.grid.ColumnModel({
                        columns: [
                        checkExtSensor,
                        {
                            header: _Alarm_Header_Name,
                            dataIndex: 'trackername',
                            width: 150
                        },
                        //            {
                        //                header: _TrackerMain_ExtProtocol,
                        //                dataIndex: 'protocol_ver',
                        //                width: 100
                        //                ,renderer:function(value, metaData, record, rowIndex, colIndex, store){
                        //                    if(value == 1)
                        //                        return _ExtSensor_Type1;
                        //                }
                        //            },
                        {
                        header: _TrackerMain_ExtSensorName,
                        dataIndex: 'expression',
                        width: 150,
                        editor: txtsensorname,
                        fixed: true
                    },
                        {
                            header: _TrackerMain_ExtSensorNumber,
                            dataIndex: 'sensor_number',
                            width: 50,
                            fixed: true
                        },
                        {
                            header: 'SN',
                            dataIndex: 'sensor_sn',
                            width: 150,
                            fixed: true
                        },
                    //            {
                    //                header: _TrackerMain_Register,
                    //                dataIndex: 'registered',
                    //                width: 70
                    //                ,renderer:function(value, metaData, record, rowIndex, colIndex, store){
                    //                    if(value)
                    //                        return _TrackerMain_Registered;
                    //                    else
                    //                        return _TrackerMain_Unregister;
                    //                }
                    //            },

                        {
                        header: _TrackerMain_MaxAlarm,
                        dataIndex: 'maxalarm',
                        width: 80,

                        editor: new Ext.form.Checkbox({

                    })
                            , renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                                if (value)
                                    return _TrackerMain_Yes;
                                else
                                    return _TrackerMain_No;
                            }
                            , fixed: true
                },
                        {
                            header: _TrackerMain_AlarmMaxValue,
                            dataIndex: 'maxvalue',
                            width: 80,
                            editor: new Ext.form.NumberField({
                                maxValue: 128,
                                minValue: -128,
                                decimalPrecision: 2
                            })
                            , fixed: true
                        },
                        {
                            header: _TrackerMain_MinAlarm,
                            dataIndex: 'minalarm',
                            width: 80,
                            editor: new Ext.form.Checkbox({

                        })
                            , renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                                if (value)
                                    return _TrackerMain_Yes;
                                else
                                    return _TrackerMain_No;
                            }
                            , fixed: true
                    },
                        {
                            header: _TrackerMain_AlarmMinValue,
                            dataIndex: 'minvalue',
                            width: 80,
                            editor: new Ext.form.NumberField({
                                maxValue: 128,
                                minValue: -128,
                                decimalPrecision: 2
                            })
                            , fixed: true
                        }, {
                            header: _TrackerMain_LastUpdate,
                            dataIndex: 'lasttime',
                            width: 120
                        }, {
                            header: _TrackerMain_CurrentTemperature,
                            dataIndex: 'lastvalue',
                            width: 80
                        },
                        this.action
                    ],
                    defaults: {
                        sortable: true,
                        menuDisabled: true,
                        width: 75
                    }
                }),
                plugins: [checkExtSensor, sensoreditor, this.action],
                viewConfig: { forceFit: true },
                stripeRows: true,
                loadMask: true,
                listeners: {
                    load: { scope: this, fn: function() {
                        this.getSelectionModel().selectFirstRow();
                    }
                    }
                }
            });
            ExtSensorList.Grid.superclass.initComponent.apply(this, arguments);
        } //end function initComponent
        , onRender: function() {
            ExtSensorList.Grid.superclass.onRender.apply(this, arguments);

        } // eo function onRender
    });

    var grid = new ExtSensorList.Grid({
        store: extsensorstore,  
        stripeRows: false,
        loadMask: true,
        title: _CustomerConfigResource_ExtSensorDefine,
        //colModel: cm,
        width:605,
        height:620,
        //plugins:[editor],
        clicksToEdit: 2,
        view: grdviewgroup,
        buttons:[btnSelectAll,btnSelectNone,btnUnregister,btnSaveFirstChoosedToAll],
        selModel:new Ext.grid.RowSelectionModel({singleSelect : true})
    });

    grid.addListener("rowdblclick", function(grid, index) {
        
    });
    
    var extsensorwin = new Ext.Window({
        title: _CustomerConfigResource_ExtSensorDefine,
        layout: 'fit',
        height: 490,
        width: 1150,
        items: grid,
        tbar: tbar,
        iconCls:'icon-sensor',
        closeAction: 'close',
        minimizable: true,
        constrain:true,
//        bbar: new Ext.PagingToolbar({
//            pageSize: pagesize,
//            store: extsensorstore,
//            beforePageText: _Alarm_Page,
//            refreshTex: _Alarm_Refresh,
//            displayMsg: _Alarm_Displaying,
//            emptyMsg: _Alarm_Alarm_emptyMsg,
//            displayInfo: true
//        }),
        listeners: {
            'minimize': function() {
                addTaskButtonForWindow(extsensorwin);
            }
        }
    });
    
    extsensorstore.on('beforeload', function(store) {
        store.baseParams = {
            sssids: trackNameCombo.getValue(),
            start: 'start',
            limit: 'limit'
            
        }
    });
    
    
    function updateExtendSensor() {
        var record = grid.getSelectionModel().getSelections()[0];

        Ext.MessageBox.show({
            msg: _CustomerConfigResource_Saving,
            progressText: _CustomerConfigResource_Saving,
            width: 300,
            wait: true,
            waitConfig: { interval: 200 }
        });
       
        Ext.Ajax.request({
            url: 'Handler/HandlerUpdateExtendSensor',
            success: function(result) {
                Ext.MessageBox.hide();
                sensoreditor.stopEditing();
                var flag = eval(result.responseText);
                if (flag == true) {
                    msgUpdateSuccess();
                }
                else {
                    msgUpdateFailure();
                }
            },
            failure: function() {
                Ext.MessageBox.hide();
                msgUpdateFailure();
            },
            params: {
                id: record.data.id,
                sssid: record.data.sssid,
                sensor_number: record.data.sensor_number,
                sensor_sn: record.data.sensor_sn,
                maxvalue:showfahrenheit?Fahrenheit2Celsius( record.data.maxvalue):record.data.maxvalue ,
                minvalue:showfahrenheit?Fahrenheit2Celsius(record.data.minvalue):record.data.minvalue,
                maxalarm:record.data.maxalarm,
                minalarm:record.data.minalarm,
                expression:record.data.expression,
                unit:record.data.unit
            }
        })
       
    }

    this.removeSensor = function(sssid, sensornumber){
        var index = extsensorstore.findBy(function(record,id){
            return record.get("sssid") == sssid && record.get("sensor_number")== parseInt(sensornumber);
        });
        if(index != -1)
            extsensorstore.removeAt(index);
    };
    
    this.changeValue= function(sssid,time,sensornumber,value){
        var index = extsensorstore.findBy(function(record,id){
            return record.get("sssid") == sssid && record.get("sensor_number")== sensornumber;
        });
        if(index != -1){
            var record = extsensorstore.getAt(index);
            record.set('lasttime',time);
            var v = parseFloat(value);
            if(showfahrenheit){
                v = Celsius2Fahrenheit(parseFloat(value));
            }
            v = v.toFixed(2);
            record.set('lastvalue',v);
        }
    };
        
    extsensorwin.show();
    
    extsensorwin.on('close',function(obj){
        g_ExtSensorWindowObject = null;
    });
    
    g_ExtSensorWindowObject = this;
}